<?php session_start(); ?>
<!-- searchScreen.php = a Module that shows search criteria form, receives user input and send to resultModule.php,  -->
<!-- assigns data to smarty template, and connects to database using PDO-Driver -->
<?php

	//defines the database type used by PDO driver
	define('DB_TYPE', 'mysql');
	//defines smarty base directory to run smarty template

	define("USER_HOME_DIR", "/home/stud/s3274282");
	require(USER_HOME_DIR . "/php/Smarty-2.6.26/Smarty.class.php");
	
	$smarty->template_dir = USER_HOME_DIR . "/.HTMLinfo/WDA/PartE/templates";
	$smarty->compile_dir = USER_HOME_DIR . "/.HTMLinfo/WDA/PartE/templates_c";
	$smarty->cache_dir = USER_HOME_DIR . "/.HTMLinfo/WDA/PartE/cache";
	$smarty->config_dir = USER_HOME_DIR . "/.HTMLinfo/WDA/PartE/configs";
	
	define('DB_HOST', 'yallara.cs.rmit.edu.au');
	define('DB_PORT', '50448'); 
	define('DB_PW', 'winestorepassword'); 
	
	define('DB_NAME', 'winestore');
	define('DB_USER', 'winestoreuser'); 
	
	$smarty = new Smarty;
	$session = $_GET["session"];
	$destroySession = $_GET["destroySession"];
	if(isset($destroySession) == true && $destroySession == "true")
	{
		$smarty->assign('message','Session Has Been Destroyed Successfully');
		session_destroy();
		echo("<META HTTP-EQUIV=\"Refresh\"
      CONTENT=\"0; URL=searchScreen.php\">");
	}
	if(isset($_SESSION['isActive']) == false)
	{
		$smarty->assign('isSessionActive','false');
	}
	if(isset($session) == true && $session == "true")
	{
		$smarty->assign('isSessionActive','true');
		$_SESSION['isActive']=true;
	}
	$queryState = "SELECT DISTINCT state FROM customer ORDER BY state";
	$queryRegion = "SELECT * FROM region ORDER BY region_name";
	$queryGrapeVariety = "SELECT * FROM grape_variety ORDER BY variety";
	$queryWineYearFromTo = "SELECT DISTINCT year FROM wine w Order by year";
	
	$smarty->assign('stateQuery',pushArray($queryState));
	$smarty->assign('regionQuery',pushArray($queryRegion));
	$smarty->assign('grapeVarietyQuery',pushArray($queryGrapeVariety));
	$smarty->assign('from',pushArray($queryWineYearFromTo));
	$smarty->assign('to',pushArray($queryWineYearFromTo));
	
	$smarty->display('searchScreen.tpl');
	
	/*
		Function to push dataset from mysql to an array so it can be assigned to smarty template
	*/
	function pushArray($query)
	{
		try 
		{
			//initialize PDO-SQL driver with defined parameter
			$db = new PDO(DB_TYPE.":host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME,DB_USER,DB_PW);
			$result = $db->query($query);//populate data from PDO driver with incoming query
			$data = array();
			foreach($result as $row)
			{
				array_push ($data, $row);//push the dataset into array
			}
			$db = null;
		}
		catch (PDOException $e)
		{
			echo $e->getMessage();
		}
			
		return $data;
	}
?>